<?php

namespace App\Jobs;

use App\Events\UserCommand;
use App\Facades\ChargeRecordManager;
use App\Facades\DeviceManager;
use App\Services\Product\DeviceService;
use App\Jobs\Job;
use App\Models\ChargeRecord;
use App\Models\Device;
use Exception;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Bus\SelfHandling;
use Illuminate\Contracts\Queue\ShouldQueue;

class CommandRepeater extends Job implements SelfHandling, ShouldQueue
{
    use InteractsWithQueue, SerializesModels;

    private $_command;
    private $_num;
    private $_deviceCode;
    private $_orderId;
    private $_userId;
    private $_throw;

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct($command, $num, $deviceCode, $orderId, $userId, $throw = false)
    {
        $this->_command = $command;
        $this->_num = $num;
        $this->_deviceCode = $deviceCode;
        $this->_orderId = $orderId;
        $this->_userId = $userId;
        $this->_throw = $throw;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        try{
            $device = DeviceManager::getDeviceByQuery('code', $this->_deviceCode);
            if(!is_null($this->_orderId)){
                $chargeRecord = ChargeRecordManager::getChageRecordById($this->_orderId);
            }
            if((!is_null($device) && $device->status == Device::STATUS_HALTING) || (isset($chargeRecord) && in_array($chargeRecord->status, [ChargeRecord::ORDER_STATUS_PAID, ChargeRecord::ORDER_STATUS_DISCHARGE]))){
                (new DeviceService)->control($this->_command, $this->_num, $this->_deviceCode, $this->_orderId, $this->_userId, $this->_throw);
            }
        }catch(Exception $e){
            if($e->getCode() == 20002){
                (new DeviceService)->control($this->_command, $this->_num, $this->_deviceCode, $this->_orderId, $this->_userId, $this->_throw);
                logger(['CommandRepeater' => $e->getMessage()]);
            }
        }

    }
}
